<?php 
require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestManager extends RestController {
    private $_MG = array();
    private $error = array();

    /*
     * 订单总入口
     */
    public function orders() {
        $this->_initMG();
        $this->checkPlugin();
        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->_getOrder($this->request->get['id']);
            }else {
                $this->_listOrders($this->request->get['page'], $this->request->get['limit'], $this->request->get['status']);
            }
        }
    }

    /*
     * 会员总入口
     */
    public function customers() {
        $this->_initMG();
        $this->checkPlugin();
        if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
            if (isset($this->request->get['id']) && ctype_digit($this->request->get['id'])) {
                $this->_getCustomer($this->request->get['id']);
            }else {
                $this->_listCustomers($this->request->get['page'], $this->request->get['limit']);
            }
        }
    }

    /*
     * 业绩分析入口
     */
    public function reportInfo() {
        $this->_initMG();
        $this->checkPlugin();
        $ret = array();
        extract($this->_getAreaList());
        $areaId = intval($this->request->get['areaId']);
        if (count($list) < 1){
            $json = array(
                'success' => false,
                'error' => array(
                    'warning' => '没有查看数据的权限',
                ),
            );
        }else{
            if (!array_key_exists($areaId, $list)) {
                $areaId = array_shift(array_keys($list));
            }
            $json = array(
                'success' => true,
                'tabList' => $list,
                'tabSelected' => $areaId,
                'gatherInfo' => $this->model_account_customer->getSaleGatherInfoInArea($areaId),
            );
        }
        $this->response->setOutput(json_encode($json));
    }

    public function saleReport() {
        $this->_initMG();
        $this->checkPlugin();
        $ret = array();
        $user['MG_saleId'] = intval($this->request->get['userId']);
        $json = array(
            'success' => true,
            'gatherInfo' => $this->model_account_customer->getSaleGatherInfo($user),
        );
        $this->response->setOutput(json_encode($json));
    }

    /*
     * 区域订单总入口
     */
    public function ordersByArea() {
        $this->_initMG();
        $this->checkPlugin();
        $ret = array();
        extract($this->_getAreaList());
        if (count($list) < 1){
            $json = array(
                'success' => false,
                'error' => array(
                    'warning' => '没有查看数据的权限',
                ),
            );
        }else{
            if (!array_key_exists($areaId, $list)) {
                $areaId = array_shift(array_keys($list));
            }
            $this->load->model('manager/order');
            $orderListTemp = $this->model_manager_order->getOrderListByArea($this->request->get['areaId'], $this->request->get['page'], $this->request->get['limit'], 'receiptWithOutPay');
            $orderStatusList = $this->model_manager_order->getOrderStatusList();
            $isPayedList = array(
                0 => '未付款',
                1 => '已付款',
            );
            $logcenterList = $this->model_manager_order->getLogcenterList();
            $warehouseList = $this->model_manager_order->getWarehouseList();
            foreach ($orderListTemp as $orderInfo) {
                $soTemp = array();
                $soTotal = 0;
                $soList = $this->model_manager_order->getStockOutByOrderId($orderInfo['order_id']);
                foreach ($soList as $soInfo) {
                    if (1 == $soInfo['status']){
                        $comment = $warehouseList[$soInfo['warehouse_id']].' 配货中';
                        $date = substr($soInfo['date_added'], 0, 10);
                    }else if (2 == $soInfo['status']){
                        $comment = $warehouseList[$soInfo['warehouse_id']].' 发往 '.$logcenterList[$orderInfo['logcenter_id']];
                        $date = substr($soInfo['out_date'], 0, 10);
                    }else if (3 == $soInfo['status']){
                        $comment = $logcenterList[$orderInfo['logcenter_id']].' 配送中';
                        $date = substr($soInfo['deliver_date'], 0, 10);
                    }else if (4 == $soInfo['status']){
                        $comment = $logcenterList[$orderInfo['logcenter_id']].' 确认签收';
                        $date = substr($soInfo['receive_date'], 0, 10);
                    }else{
                        break;
                    }
                    $soTemp[] = array(
                        'soId' => $soInfo['out_id'],
                        'total' => $soInfo['sale_money'],
                        'comment' => $comment,
                        'date' => $date,
                    );
                    $soTotal += $soInfo['sale_money'];
                }
                $temp = array(
                    'orderId' => $orderInfo['order_id'],
                    'total' => number_format($orderInfo['total'], 2),
                    'soTotal' => number_format($soTotal, 2),
                    'shippingInfo' => array(
                        $orderInfo['shipping_fullname'].' - '.$orderInfo['shipping_company'],
                        //'地　址： '.$orderInfo['shipping_country'].$orderInfo['shipping_zone'].$orderInfo['shipping_city'].$orderInfo['shipping_address'],
                    ),
                    'paymentCode' => $orderInfo['payment_code'],
                    'paymentMethod' => $orderInfo['payment_method'],
                    'logcenter' => $logcenterList[$orderInfo['logcenter_id']],
                    'status' => $orderStatusList[$orderInfo['order_status_id']].'（'.$isPayedList[$orderInfo['is_pay']].'）',
                    'isPay' => ($orderInfo['is_pay'])?'green':'red',
                    'dateAdded' => substr($orderInfo['date_added'], 0, 10),
                    'soList' => $soTemp,
                );
                $orderList[] = $temp;
            }


            $json = array(
                'success' => true,
                'tabList' => $list,
                'tabSelected' => $areaId,
                'orders' => $orderList,
            );
        }
        $this->response->setOutput(json_encode($json));
    }

    /*
     * 初始化会员信息
     */
    private function _initMG() {
        $this->load->model('account/customer');
        if (!$this->customer->isLogged()) {
            $json["error"]['warning']= "用户没有登陆";
            $json["success"] = false;
            $this->response->setOutput(json_encode($json));
        }else{
            $user = $this->model_account_customer->getCustomer($this->customer->getId());
            $this->_MG = $this->model_account_customer->userCheckByTelephone($user['telephone']);
            if ($this->_MG['MG_userId'] < 1) {
                $json["error"]['warning']= "没有操作权限";
                $json["success"] = false;
                $this->response->setOutput(json_encode($json));
            }
        }
    }

    /*
     * 根据 业务员编号（MG_saleId）获取订单列表
     */
    protected function _listOrders($page, $limit, $status) {
        $json = array('success' => true, 'orders' => array());
        if ($this->_MG['MG_saleId'] > 0) {
            $this->load->model('manager/order');
            $orderList = $this->model_manager_order->getOrdersListBySaleId($this->_MG['MG_saleId'], $page, $limit, $status);
            $orderStatusList = $this->model_manager_order->getOrderStatusList();
            $isPayedList = array(
                0 => '未付款',
                1 => '已付款',
            );
            $logcenterList = $this->model_manager_order->getLogcenterList();
            $warehouseList = $this->model_manager_order->getWarehouseList();
            foreach ($orderList as $orderInfo) {
                $soTemp = array();
                $soTotal = 0;
                $soList = $this->model_manager_order->getStockOutByOrderId($orderInfo['order_id']);
                foreach ($soList as $soInfo) {
                    if (1 == $soInfo['status']){
                        $comment = $warehouseList[$soInfo['warehouse_id']].' 配货中';
                        $date = substr($soInfo['date_added'], 0, 10);
                    }else if (2 == $soInfo['status']){
                        $comment = $warehouseList[$soInfo['warehouse_id']].' 发往 '.$logcenterList[$orderInfo['logcenter_id']];
                        $date = substr($soInfo['out_date'], 0, 10);
                    }else if (3 == $soInfo['status']){
                        $comment = $logcenterList[$orderInfo['logcenter_id']].' 配送中';
                        $date = substr($soInfo['deliver_date'], 0, 10);
                    }else if (4 == $soInfo['status']){
                        $comment = $logcenterList[$orderInfo['logcenter_id']].' 确认签收';
                        $date = substr($soInfo['receive_date'], 0, 10);
                    }else{
                        break;
                    }
                    $soTemp[] = array(
                        'soId' => $soInfo['out_id'],
                        'total' => $soInfo['sale_money'],
                        'comment' => $comment,
                        'date' => $date,
                    );
                    $soTotal += $soInfo['sale_money'];
                }
                $temp = array(
                    'orderId' => $orderInfo['order_id'],
                    'total' => number_format($orderInfo['total'], 2),
                    'soTotal' => number_format($soTotal, 2),
                    'shippingInfo' => array(
                        $orderInfo['shipping_fullname'].' - '.$orderInfo['shipping_company'],
                        //'地　址： '.$orderInfo['shipping_country'].$orderInfo['shipping_zone'].$orderInfo['shipping_city'].$orderInfo['shipping_address'],
                    ),
                    'paymentCode' => $orderInfo['payment_code'],
                    'paymentMethod' => $orderInfo['payment_method'],
                    'logcenter' => $logcenterList[$orderInfo['logcenter_id']],
                    'status' => $orderStatusList[$orderInfo['order_status_id']].'（'.$isPayedList[$orderInfo['is_pay']].'）',
                    'isPay' => ($orderInfo['is_pay'])?'green':'red',
                    'dateAdded' => substr($orderInfo['date_added'], 0, 10),
                    'soList' => $soTemp,
                );
                $json['orders'][] = $temp;
            }
        }
        //echo json_encode($json);
        $this->response->setOutput(json_encode($json));
    }

    /*
     * 根据 业务员编号（MG_saleId）、订单编号 获取订单详情
     */
    protected function _getOrder($order_id) { 
        if ($this->_MG['MG_saleId'] > 0) {
            $this->load->model('manager/order');
            $orderInfo = $this->model_manager_order->getOrderInfoBySaleId($this->_MG['MG_saleId'], $order_id);
            $orderStatusList = $this->model_manager_order->getOrderStatusList();
            $isPayedList = array(
                0 => '未付款',
                1 => '已付款',
            );
            $logcenterList = $this->model_manager_order->getLogcenterList();
            $warehouseList = $this->model_manager_order->getWarehouseList();
            $HS = 'http://m.bhz360.com/';
            if ($order_id == $orderInfo['order_id']) {
                $soTemp = array();
                $soTotal = 0;
                $soList = $this->model_manager_order->getStockOutByOrderId($orderInfo['order_id']);
                foreach ($soList as $soInfo) {
                    if (1 == $soInfo['status']){
                        $comment = $warehouseList[$soInfo['warehouse_id']].' 配货中';
                        $date = substr($soInfo['date_added'], 0, 10);
                    }else if (2 == $soInfo['status']){
                        $comment = $warehouseList[$soInfo['warehouse_id']].' 发往 '.$logcenterList[$orderInfo['logcenter_id']];
                        $date = substr($soInfo['out_date'], 0, 10);
                    }else if (3 == $soInfo['status']){
                        $comment = $logcenterList[$orderInfo['logcenter_id']].' 配送中';
                        $date = substr($soInfo['deliver_date'], 0, 10);
                    }else if (4 == $soInfo['status']){
                        $comment = $logcenterList[$orderInfo['logcenter_id']].' 确认签收';
                        $date = substr($soInfo['receive_date'], 0, 10);
                    }else{
                        break;
                    }
                    $sopTemp = array();
                    $sopList = $this->model_manager_order->getStockOutProductsBySoId($soInfo['out_id']);
                    foreach ($sopList as $sopInfo) {
                        $sopTemp[] = array(
                            'image' => ($sopInfo['image'])?$HS.'image/'.$sopInfo['image']:'',
                            'name' => $sopInfo['name'].(($sopInfo['pg_name'])?'('.$sopInfo['pg_name'].')':''),
                            'price' => $sopInfo['price'],
                            'qty' => $sopInfo['qty'],
                            'total' => $sopInfo['total'],
                       );
                    }
                    $soTemp[] = array(
                        'soId' => $soInfo['out_id'],
                        'total' => $soInfo['sale_money'],
                        'comment' => $comment,
                        'date' => $date,
                        'sopList' => $sopTemp,
                    );
                    $soTotal += $soInfo['sale_money'];
                }
                $tlTemp = array();
                $tlList = $this->model_manager_order->getOrderTotals($orderInfo['order_id']);
                foreach ($tlList as $tlInfo) {
                    $tlTemp[] = array(
                        'title' => $tlInfo['title'],
                        'value' => number_format($tlInfo['value'], 2),
                    );
                }
                $opTemp = array();
                $opList = $this->model_manager_order->getOrderProducts($orderInfo['order_id']);
                foreach ($opList as $k=>$opInfo) {
                    $opTemp[$k] = array(
                        'name' => $opInfo['name'],
                        'image' => ($opInfo['image'])?$HS.'image/'.$opInfo['image']:'',
                        'price' => number_format($opInfo['price'], 2),
                        'qty' => $opInfo['quantity'],
                        'total' => number_format($opInfo['price']*$opInfo['quantity'], 2),
                        'lackQty' => ($opInfo['lack_quantity'])?$opInfo['lack_quantity'].'未发':'',
                        'childProducts' => array(),
                    );
                    if (2 == $opInfo['product_type']) {
                        $opTemp[$k]['lackQty'] = '';
                        $opgTemp = array();
                        $opgList = $this->model_manager_order->getOrderProductsGroup($opInfo['order_product_id']);
                        foreach ($opgList as $opgInfo) {
                            $opgTemp[] = array(
                                'name' => $opgInfo['name'],
                                'image' => ($opgInfo['image'])?$HS.'image/'.$opgInfo['image']:'',
                                'price' => number_format($opgInfo['price'], 2),
                                'qty' => $opgInfo['quantity'],
                                'total' => number_format($opgInfo['price']*$opgInfo['quantity'], 2),
                                'lackQty' => ($opgInfo['lack_quantity'])?$opgInfo['lack_quantity'].'未发':'全部发货',
                            );
                        }
                        $opTemp[$k]['childProducts'] = $opgTemp;
                    }
                }
                $temp = array(
                    'orderId' => $orderInfo['order_id'],
                    'total' => number_format($orderInfo['total'], 2),
                    'soTotal' => number_format($soTotal, 2),
                    'shippingInfo' => array(
                        '收货人： '.$orderInfo['shipping_fullname'].' ('.$orderInfo['shipping_telephone'].') '.$orderInfo['shipping_company'],
                        '地　址： '.$orderInfo['shipping_country'].$orderInfo['shipping_zone'].$orderInfo['shipping_city'].$orderInfo['shipping_address'],
                    ),
                    'paymentCode' => $orderInfo['payment_code'],
                    'paymentMethod' => $orderInfo['payment_method'],
                    'logcenter' => $logcenterList[$orderInfo['logcenter_id']],
                    'status' => $orderStatusList[$orderInfo['order_status_id']].'（'.$isPayedList[$orderInfo['is_pay']].'）',
                    'isPay' => ($orderInfo['is_pay'])?'green':'red',
                    'dateAdded' => $orderInfo['date_added'],
                    'soList' => $soTemp,
                    'totalList' => $tlTemp,
                    'opList' => $opTemp,
                );
                $json = array('success' => true, 'order' => $temp);
            }else{
                $json['success'] = false;
                $json['error']['warning'] = "这个订单不存在";
            }
        }else{
            $json['success'] = false;
            $json['error']['warning'] = "这个订单不存在";
        }
        $this->response->setOutput(json_encode($json));
    }

    /* 
     * 根据 业务员编号（MG_saleId）获取会员列表
     */
    protected function _listCustomers($thisPage, $limit) {
        $json = array('success' => true, 'customers' => array());
        if ($this->_MG['MG_saleId'] > 0) {
            $this->load->model('manager/customer');
            $json['data']['customers'] = array();
            $shopTypes = getShopTypes();
            $results = $this->model_manager_customer->getCustomersBySaleId($this->_MG['MG_saleId'], $thisPage, $limit);
            foreach ($results as $result) {
                $json['customers'][] = array(
                    'customer_id'       => $result['customer_id'],
                    'fullname'          => $result['fullname'],
                    'telephone'         => $result['telephone'],
                    'company'           => $result['company_name'],
                    'shop_type'         => $shopTypes[$result['shop_type']],
                    'order_sum'         => $result['order_sum'],
                    'last_order_date'   => $result['last_order_date'],
                    'default_address'   => array(
                        'company'   => $result['AC'],
                        'address'   => $result['AA'],
                        'fullname'  => $result['AN'],
                        'telephone' => $result['AT'],
                    ),
                );
            }
        }
        $this->response->setOutput(json_encode($json));
    }

    /* 
     * 根据 业务员编号（MG_saleId）、会员编号 获取会员详情
     */
    protected function _getCustomer($customerId) {}

    /* 
     * 根据 用户编号（MG_userId），获取有统计权限的区域列表
     */
    protected function _getAreaList() {
        $default = false;
        $list = array();
        $this->load->model('manager/sales_area');
        $allSalesArea = $this->model_manager_sales_area->getAllSalesArea();
        foreach ($allSalesArea as $areaInfo) {
            if (($this->_MG['MG_userId'] == $areaInfo['manager']) || (false !== strpos($areaInfo['manager_assistant'], ','.$this->_MG['MG_userId'].',')) || (false !== strpos($areaInfo['view_report'], ','.$this->_MG['MG_userId'].','))) {
                $list[$areaInfo['sales_area_id']] = $areaInfo['name'];
                if (false === $default) {
                    $default = $areaInfo['sales_area_id'];
                }
            }
        }
        if (count($list) && count($list) == count($allSalesArea)) {
            $list[0] = '全部';
            $default = 0;
            ksort($list);
        }
        return compact('default', 'list');
    }
}
